package me.shiqiang.im.utils;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 倒计时工具
 *
 * @author cuishiqiang
 * @date 2017/12/14 上午10:17
 */
public abstract class CountDownTimer {
    /**
     * 倒计时时长，毫秒为单位，应设为步长的整数倍
     */
    private final long time;

    /**
     * 指定步长，毫秒为单位，倒计时每减少步长时间触发 onTick 方法
     * 倒计时时长应设为步长的整数倍
     */
    private final long countdownInterval;

    private volatile long stopTimeInFuture;

    private boolean cancelled = false;

    private AtomicLong count = new AtomicLong(0);

    public long increment() {
         return count.incrementAndGet();
    }

    public long getCount() {
        return count.get();
    }


    private Timer timer = new Timer();


    public CountDownTimer(long time, long countdownInterval) {
        this.time = time;
        this.countdownInterval = countdownInterval;
    }

    /**
     * 取消倒计时
     */
    public synchronized final void cancel() {
        cancelled = true;
    }

    /**
     * 开始倒计时
     */
    public synchronized final CountDownTimer start() {
        cancelled = false;
        if (time <= 0) {
            onFinish();
            return this;
        }
        stopTimeInFuture = System.currentTimeMillis() + time;
        timer.schedule(new TimerTask() {
            public void run() {
                if (cancelled) {
                    timer.cancel();
                }
                long timeLeft = stopTimeInFuture - System.currentTimeMillis();
                if (timeLeft <= 0) {
                    timer.cancel();
                    onFinish();
                } else {
                    onTick(timeLeft);
                }
            }
        }, 0, countdownInterval);
        return this;
    }

    /**
     * 步长触发onTick
     *
     * @param millisUntilFinished 距离倒计时结束还剩时间
     */
    public abstract void onTick(long millisUntilFinished);

    /**
     * 倒计时结束时触发此事件方法
     */
    public abstract void onFinish();
}
